import java.io.File;
import java.util.LinkedList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class OracleXML extends Oracle{
	
	private int N;
	private List<Monom> monoms;
	
	public OracleXML(String xmlFile, int N){
		this.N = N;
		monoms = new LinkedList<Monom>();
		double real;
		double im;
		int alpha;
		
		try {
			   File file = new File(xmlFile);
			   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			   DocumentBuilder db = dbf.newDocumentBuilder();
			   Document doc = db.parse(file);
			   doc.getDocumentElement().normalize();
			   
			   Element ele = doc.getDocumentElement();
			   String functionID = ele.getAttribute("id");
			   NodeList nodeLst = ele.getElementsByTagName("function");
			   
			   for (int s = 0; s < nodeLst.getLength(); s++) { 
			   
				   Node currNode = nodeLst.item(s);
				   
				   Element funcElem = (Element) currNode;
				   if(funcElem.getAttribute("id").equalsIgnoreCase(functionID)){
					   NodeList monomLst = funcElem.getElementsByTagName("monom");
				     
				   for(int i=0;i < monomLst.getLength(); i++){
					   NodeList reals = funcElem.getElementsByTagName("real");
					   real = new Double(reals.item(i).getTextContent());
					   NodeList ims = funcElem.getElementsByTagName("image");
					   im = new Double(ims.item(i).getTextContent());
					   NodeList alphas = funcElem.getElementsByTagName("alpha");
					   alpha = new Integer(alphas.item(i).getTextContent());
					   
					   System.out.println("real: "+real+" im: "+im+" alpha: "+alpha);
					   monoms.add(new Monom(real, im, alpha));
				   }
			   }
		   }
			  
		}
		
		catch (Exception e) {
			     e.printStackTrace();
		}
			    
	}
	
	public Complex query(int q){
		Complex ret = new Complex(0,0);
		for(int i = 0; i < this.monoms.size(); i++){
			ret = ComplexOperations.addComplex(ret, this.monoms.get(i).charFunc(this.N, q));
		}
		return ret;
	}
	
}
